import 'package:flutter/material.dart';
import 'package:todo_app/components/Button/CustomElevateButton.dart';
import 'package:todo_app/components/Overlay/main.dart';
import 'package:todo_app/constants/DColor.dart';
import 'package:todo_app/layout/Gaps.dart';
import 'package:todo_app/layout/ListItem.dart';
import 'package:todo_app/layout/Header.dart';

typedef Widget TitleBuilder<T>(T item);
class OptionItem<T> {
  final T value;
  final String label;

  OptionItem({
    required this.value, 
    required this.label
  });
}

typedef void CheckedOptionCallback<T>(bool checked, T value, List<T> checkedIds);

class OptionsPicker<T> extends StatefulWidget {
  OptionsPicker({ Key? key, required this.options, this.title = "选择", this.multiSelect = true, required this.checkedIds }) : super(key: key);

  final List<OptionItem<T>> options;
  final String title;
  final bool multiSelect;
  final List<T> checkedIds;

  @override
  State<OptionsPicker<T>> createState() => _OptionsPickerState<T>();
}

class _OptionsPickerState<T> extends State<OptionsPicker<T>> {
  List<T> checkedIds = [];

  @override
  void initState() {
    this.checkedIds = widget.checkedIds;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: Header(
        title: widget.title,
        actions: [
          CustomElevateButton(
            child: Text("确定"), 
            width: 80.dp, 
            height: 32.dp,
            bgColor: DColor.second,
            borderRadius: 3.dp,
            onTap: () {
              if(checkedIds.length == 0) {
                showOverlayToast("请先选择一项再点击确定");
                return;
              }
              Navigator.of(context).pop(this.checkedIds);
            },
          )
        ],
      ),
      body: ListView(
        children: widget.options.map<Widget>((e) {
          bool checked = this.checkedIds.contains(e.value);
          return ListItem(
            height: 48.dp,
            title: Text(e.label),
            border: true,
            content: Icon(
              checked ? Icons.check_box_rounded : Icons.check_box_outline_blank_outlined,
              color: checked ? DColor.primary : DColor.gray,
              size: 24.dp,
            ),
            onTap: () {
              if(widget.multiSelect) {
                if(!checked) {
                  this.checkedIds.add(e.value);
                } else {
                  this.checkedIds.remove(e.value);
                }
              } else {
                this.checkedIds = [e.value];
              }
              setState(() {});
            },
          );
        }).toList(),
      ),
    );
  }
}